# face_recognition 人脸检测并识别，显示人名
import cv2

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer.yml')
cascadePath = "haarcascade_frontalface_alt.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
font = cv2.FONT_HERSHEY_SIMPLEX
# 这里为0或者1都没有关系
idnum = 0
#names = ['LIANG',"LUO","CHENG"]
names = ['YU',"ZHANG","LUO"]
# names中存储人的名字，若该人id为0则他的名字在第一位，id为1则排在第二位，以此类推
cam = cv2.VideoCapture(0)

while True:
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray,1.3,5)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 100), 3)
        idnum, confidence = recognizer.predict(gray[y:y+h, x:x+w])
        if confidence > 30:
            idnum = names[idnum]
            confidence = "{0}%".format(round(confidence))
            cv2.putText(img, str(idnum), (x + 5, y - 5), font, 3,
                        (0, 255, 255), 3)
            cv2.putText(img, str(confidence), (x + 5, y + h - 5), font,
                        3,(255, 255, 0), 2)
        else:
            idnum = "unknown"
            confidence = "{0}%".format(round(confidence))

    cv2.imshow('camera', img)
    k = cv2.waitKey(10)
    if k == 27:
        break

cam.release()
cv2.destroyAllWindows()
